package com.example.springblog.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.example.springblog.constant.Constants;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.model.UserVO;
import com.example.springblog.service.UserService;
import com.example.springblog.utils.JwtUtils;
import com.example.springblog.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 获取验证码
     * @param session
     * @param response
     */
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(Constants.CAPTCHA_WIDTH, Constants.CAPTCHA_HEIGHT, Constants.CAPTCHA_CODE_COUNT, Constants.CAPTCHA_THICKNESS);
        // 设置返回数据类型
        response.setContentType("image/jpeg");
        // 禁止使用缓存
        response.setHeader("Pragma", "No-cache");
        try {
            // 输出到页面
            captcha.write(response.getOutputStream());
            // 将 生成的验证码 和 验证码生成时间 存储到session中
            session.setAttribute(Constants.CAPTCHA_KEY, captcha.getCode());
            session.setAttribute(Constants.CAPTCHA_DATE, new Date());
            // 关闭流
            response.getOutputStream().close();
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用户登录
     * @param userName
     * @param password
     * @param captcha
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(String userName, String password, String captcha, HttpSession session) {
        log.info("用户登录，获取到参数 userName:{}, password:{}, captcha:{}", userName, password, captcha);
        // 参数校验
        if(!StringUtils.hasLength(captcha)) {
            return Result.fail("验证码不能为空!");
        }
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空!");
        }

        // 判断验证码是否正确
        String result = userService.isCorrectCaptcha(captcha, session);
        if(result != null) {
            return Result.fail(result);
        }

        // 根据用户名查询
        UserInfo userInfo = userService.selectByName(userName);
        // 用户名是否存在
        if(userInfo == null) {
            return Result.fail("用户名或密码错误!");
        }
        // 密码是否正确
        if(!SecurityUtils.verity(password, userInfo.getPassword())) {
            return Result.fail("密码错误!");
        }
        // 密码正确，返回token
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID, userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME, userName);
        String token = JwtUtils.genJwt(claim);
        log.info("UserController 返回token:{}", token);
        return Result.success(token);
    }

    /**
     * 用户注册
     * @param userName
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result<String> register(String userName, String password) {
        log.info("用户注册，获取到参数 userName:{}, password: {}", userName, password);
        // 参数校验
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空!");
        }
        try {
            int result = userService.insertUser(userName, password);
            if(result > 0) {
                return Result.success("");
            }
            return Result.fail("内部错误,请联系管理员");
        }catch (org.springframework.dao.DuplicateKeyException e){
            return Result.fail("用户名已存在!");
        }
    }

    /**
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result<UserVO> getUserInfo(HttpServletRequest request) {
        log.info("从token中获取当前登录用户信息");
        // 从 request 中获取token
        String jwtToken = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        // 从 token 中获取用户id
        Integer userId = JwtUtils.getUerIdFromToken(jwtToken);
        // 获取用户信息
        if(userId != null) {
            UserVO userInfo = userService.getUserInfo(userId);
            if(userInfo != null) {
                return Result.success(userInfo);
            }
        }
        return Result.fail("获取当前用户信息失败!");
    }

    /**
     * 获取博客作者信息
     * @param blogId
     * @return
     */
    @GetMapping("/getAuthorInfo")
    public Result<UserVO> getAuthorInfo(Integer blogId) {
        log.info("获取博客作者信息, 参数blogId:{}", blogId);
        // 参数校验
        if(blogId == null || blogId <= 0) {
            return Result.fail("博客id有误!");
        }
        // 获取作者相关信息
        UserVO userInfo = userService.getUserInfoByBlogId(blogId);
        if(userInfo != null) {
            return Result.success(userInfo);
        }
        return Result.fail("获取作者信息失败!");
    }
}
